package com.zbxj.wyz.service;

import com.zbxj.wyz.domain.Exam;
import com.zbxj.wyz.domain.dto.ExamDto;
import com.zbxj.wyz.domain.dto.Result;
import com.zbxj.wyz.mapper.ExamMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Service
public class ExamService {
    @Autowired
    CourseService courseService;

    @Autowired
    ExamDataService examDataService;

    @Autowired
    ExamMapper examMapper;

    public Result getExamByCourseName(String courseName){
        List<ExamDto> examDtoList = examMapper.getExamByCourseName(courseName);
        if (!examDtoList.isEmpty())
            return new Result<List<ExamDto>>().ok("获取试卷列表成功",examDtoList);
        else
            return new Result().serverError("获取试卷列表失败");
    }

    public String getExamNameByExamId(int examId){
        return examMapper.getExamNameByExamId(examId);
    }

    //返回的是是否成功修改
    private int addExam(Exam exam){
        return examMapper.addExam(exam);
    }

    public Result addExamAndProblem(@RequestBody ExamDto examDto){
        int courseId = courseService.getIdByCourseName(examDto.getCourseName());
        Exam exam = examDto.toExam(courseId,examDto);
        addExam(exam);

        //如果uuId列表为空，则只添加试卷，不添加数据
        if(examDto.getUuIdList().isEmpty())
            return new Result<List<Object>>().ok("创建试卷（不含题目）成功");

        //如果uuId列表不为空，则添加题目到试卷
        int examId = exam.getExamId();
        if(examDataService.addProbelmListToExam(examId,examDto.getUuIdList()).getCode()==200)
            return new Result<List<Object>>().ok("创建试卷（含题目）成功");
        else
            return new Result().serverError("创建试卷（含题目）失败");
    }

    public Result deleteExam(Exam exam){
        if(examMapper.deleteExam(exam) > 0)
            return new Result().ok("删除试卷成功");
        else
            return new Result().serverError("删除试卷失败");
    }

    public Result updateExam(Exam exam){
        if(examMapper.updateExam(exam) > 0)
            return new Result().ok("修改试卷成功");
        else
            return new Result().serverError("修改试卷失败");
    }
}
